#pragma once
#include "Protocol.hpp"
#include<functional>

using handler_t = std::function<Response(Request &)>;

class Parser
{
public:
    Parser(handler_t handler):_handler(handler)
    {}
    std::string Parse(std::string &inbuffer)
    {
        std::string sendstr;

        while (true) // 可能其中存在多个完整报文
        {
            std::string reqstr;
            int n = Protocol::Unpack(inbuffer, &reqstr);
            if (n == 0)
                 break;
            else if (n == -1)
                exit(0); // 协议错误
            else
            {
                // 报文请求成功
                // 反序列
                Request req;
                if(!req.Deserialze(reqstr))
                {
                    return std::string();
                }
                // 处理请求返回应答
                Response resp = _handler(req);
                // 将应答序列化
                std::string resp_json;
                if(!resp.Seriailze(&resp_json))
                {
                    return std::string();
                }
                // 将应答打包
                sendstr += Protocol::Package(resp_json);

            }
        }
        LOG(LogLevel::DEBUG) << "获取报文成功: " << sendstr;

        return sendstr;
    }
    ~Parser()
    {}
public:
    handler_t _handler;
};